from odoo import api, fields, models
from odoo.exceptions import ValidationError
import json


class SubcontractionQtyWizard(models.TransientModel):
    _inherit = 'subcontracting.qty.wizard'

    def _make_data(self):
        """mes data"""
        data = [{'org_id': '0001',
                'help_code': self.order_id.sb_subcontracting_apply_id.mes_order,
                'break_cause': '无',
                "mo_list": [{
                    "mo_code": l.purchase_order_line_id.workorder_id.production_id.name,
                    "pcs_qty": l.qty_received * l.purchase_order_line_id.workorder_id.value_pnl,
                    "pnl_qty": l.qty_received,
                    "set_qty": l.qty_received * l.purchase_order_line_id.workorder_id.value_set,
                    "wp_code": l.subcon_line_id.stop_workorder_id.workcenter_id.code if self.is_all_outside else l.purchase_order_line_id.workorder_id.workcenter_id.code
                } for l in self.line_ids]}]
        return {
            "docType": "API_OUT_HELP_END",
            "updateType": "UPDATE",
            "data": data
        }

    def button_confirm(self):
        res = super().button_confirm()
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            try:
                data = self._make_data()
                self.env['s.mes.upload'].with_delay(description='外发接收同步mes').upload_data(data)
                self.subcon_outside_id.sync_json = json.dumps(data)
            except Exception as e:
                raise ValidationError(str(e))
        return res

    def button_confirm02(self):
        res = super().button_confirm02()
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            try:
                data = self._make_data()
                self.env['s.mes.upload'].with_delay(description='外发接收同步mes').upload_data(data)
                self.subcon_outside_id.sync_json = json.dumps(data)
            except Exception as e:
                raise ValidationError(str(e))
        return res